#各种工具文件
import os
from tqdm import tqdm

'''
flage
+-------------------------------------------------------------------------------------------------+
0:使得两个文件夹下的前缀名一一对应，通常用来对标签文件和图片文件规范化名字，也可防止含有空格等不规范名。
例如文件夹A:jintian.jpg，文件夹B:jintian.json
+-------------------------------------------------------------------------------------------------+
1:删除多余的文件名
例如原文件名为0x4j340.jpg.json，更改为0x4j340.json
+-------------------------------------------------------------------------------------------------+
2:labelme的新的标注文件json，写入到该图对应的原来旧标签json文件中,新的json必须是labelme标注工具标注的json，且需
要保证旧文件和新文件里的名字一一对应
+-------------------------------------------------------------------------------------------------+

'''
flag = 0
def normalize_file_name(dir1:str,dir2:str):
    delete_list = []
    renamed1_dict = {}
    renamed2_dict = {}
    file_names1 = os.listdir(dir1)
    file_names2 = os.listdir(dir2)

    for index1, name1 in tqdm(enumerate(file_names1), ncols=100, total=len(file_names1)):
        baseName1 = ''.join(name1.split(".")[:-1])
        name1_path = os.path.join(dir1, name1)
        postfix_name1 = "."+name1.split(".")[-1]
        for index2, name2 in enumerate(file_names2):
            baseName2 = ''.join(name2.split(".")[:-1])
            name2_path = os.path.join(dir2,name2)
            postfix_name2 = "."+name2.split(".")[-1]

            flag = False
            if baseName2 == baseName1:
                rename = str(index1)+str(index2)
                renamed1_dict[name1] = rename+postfix_name1
                renamed2_dict[name2] = rename+postfix_name2
                flag = True
                break
        if not flag:  # dir1的文件是否在dir2中也存在，如果不存在，则删除，用来确保两个文件夹里的文件前缀名是一一对应的
            delete_list.append(name1_path)

    for k, v in renamed2_dict.items():
        os.rename(os.path.join(dir2, k), os.path.join(dir2, v))
    for k, v in renamed1_dict.items():
        os.rename(os.path.join(dir1, k), os.path.join(dir1, v))
    for i in delete_list:
        os.remove(i)

def delete_posix(path:str,correct_postfix:str,error_postfix:list):
    '''
    path:文件夹路径
    correct_postfix:正确的文件后缀名,只会对以这种文件进行处理
    error_postfix:不要的文件后缀名
    '''
    all_fileNames = os.listdir(path)
    for fileName in all_fileNames:
        if fileName.endswith(correct_postfix):
            file_prefix = fileName[:-(len(correct_postfix)+1)]

            file_prefix_postfix = file_prefix.split(".")[-1]
            if file_prefix_postfix in error_postfix:
                new_file_name = "".join(file_prefix.split(".")[:-1])
                new_full_path = os.path.join(path,new_file_name)+"."+correct_postfix
                old_full_path = os.path.join(path,fileName)
                os.rename(old_full_path,new_full_path)

def jsonToJson(path_old_json,path_new_json):
    for json_name in os.listdir(path_new_json):
        old_jsonFile = os.path.join(path_old_json, json_name)
        new_jsonFile = os.path.join(path_new_json, json_name)

        with open(old_jsonFile) as f:
            lines = json.load(f)

            with open(new_jsonFile) as f1:
                lines2 = json.load(f1)
                for line in lines2['shapes']:
                    del line['group_id']
                    del line['shape_type']
                    del line['flags']
                    line['points'] = [[round(i, 1), round(j, 1)] for i, j in line['points']]
                    line['polygon'] = line.pop('points')
                    lines['objects'].append(line)

                with open(old_jsonFile, 'w') as f2:
                    json.dump(lines, f2)

if __name__ == "__main__":
    if flag == 0:
        dir2 = "/home/xys/CloundShiProjects/traffic_light/trafficlight_dect/data/JPEGImages"
        dir1 = "/home/xys/CloundShiProjects/traffic_light/trafficlight_dect/data/xml"
        normalize_file_name(dir2,dir1)
    elif flag == 1:
        path = "/media/jiji/3b75ab20-92d3-4be6-81c2-4e1798e2fe16/公司/DeepLabv3_data/val/json(副本)"
        delete_posix(path,"json",["jpg","png","jpeg"])
    elif flag == 2:
        import json
        path_old_json = "/media/jiji/3b75ab20-92d3-4be6-81c2-4e1798e2fe16/公司/DeepLabv3_data/val/新建文件夹/old"  # 旧文件
        path_new_json = "/media/jiji/3b75ab20-92d3-4be6-81c2-4e1798e2fe16/公司/DeepLabv3_data/val/新建文件夹/new"  # 新文件
        jsonToJson(path_old_json,path_new_json)




